//
//  BottomPopupView.m
//  Tunnel
//
//  Created by wbb on 2025/6/10.
//

#import "BottomPopupView.h"
@interface BottomPopupView () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSArray<NSString *> *items;
@property (nonatomic, assign) NSInteger selectedIndex;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIButton *backgroundButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, weak) UIViewController *parentViewController;
@property (nonatomic, copy) BottomPopupViewCompletion completion;

@end


@implementation BottomPopupView

+ (instancetype)pickerPopupWithTitle:(NSString *)title
                              items:(NSArray<NSString *> *)items
                      selectedIndex:(NSInteger)selectedIndex {
    BottomPopupView *popup = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
    popup.title = title;
    popup.items = items;
    popup.selectedIndex = selectedIndex;
    [popup setupViews];
    return popup;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setupViews {
    // 背景按钮，用于点击外部区域关闭弹出框
    self.backgroundButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backgroundButton.frame = self.bounds;
    self.backgroundButton.backgroundColor = [UIColor blackColor];
    self.backgroundButton.alpha = 0.0;
    [self.backgroundButton addTarget:self action:@selector(backgroundButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.backgroundButton];
    
    // 容器视图
    self.containerView = [[UIView alloc] init];
    self.containerView.backgroundColor = [UIColor whiteColor];
    self.containerView.layer.cornerRadius = 15.0;
    self.containerView.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    self.containerView.clipsToBounds = YES;
    [self addSubview:self.containerView];
    
    // 顶部标题视图
    UIView *titleView = [[UIView alloc] init];
    titleView.backgroundColor = [UIColor whiteColor];
    [self.containerView addSubview:titleView];
    
    // 标题标签
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = self.title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:18.0 weight:UIFontWeightMedium];
    [titleView addSubview:titleLabel];
    
    // 取消按钮
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0] forState:UIControlStateNormal];
    self.cancelButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [self.cancelButton addTarget:self action:@selector(cancelButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:self.cancelButton];
    
    // 确定按钮
    self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:[UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    self.confirmButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [self.confirmButton addTarget:self action:@selector(confirmButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:self.confirmButton];
    
    // 分隔线
    UIView *separatorView = [[UIView alloc] init];
    separatorView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    [titleView addSubview:separatorView];
    
    // 选择器视图
    self.pickerView = [[UIPickerView alloc] init];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.containerView addSubview:self.pickerView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat titleHeight = 50.0;
    CGFloat pickerHeight = 216.0; // UIPickerView的标准高度
    CGFloat totalHeight = titleHeight + pickerHeight;
    
    // 设置容器视图的初始位置（在屏幕下方）
    CGRect containerFrame = CGRectMake(0, self.bounds.size.height, self.bounds.size.width, totalHeight);
    self.containerView.frame = containerFrame;
    
    // 设置标题视图
    CGRect titleViewFrame = CGRectMake(0, 0, self.bounds.size.width, titleHeight);
    UIView *titleView = self.containerView.subviews[0];
    titleView.frame = titleViewFrame;
    
    // 设置标题标签
    UILabel *titleLabel = titleView.subviews[0];
    titleLabel.frame = CGRectMake(60, 0, self.bounds.size.width - 120, titleHeight);
    
    // 设置取消按钮
    self.cancelButton.frame = CGRectMake(16, 0, 40, titleHeight);
    
    // 设置确认按钮
    self.confirmButton.frame = CGRectMake(self.bounds.size.width - 56, 0, 40, titleHeight);
    
    // 设置分隔线
    UIView *separatorView = titleView.subviews[3];
    separatorView.frame = CGRectMake(0, titleHeight - 0.5, self.bounds.size.width, 0.5);
    
    // 设置选择器视图
    self.pickerView.frame = CGRectMake(0, titleHeight, self.bounds.size.width, pickerHeight);
    
    // 设置默认选中项
    if (self.selectedIndex >= 0 && self.selectedIndex < self.items.count) {
        [self.pickerView selectRow:self.selectedIndex inComponent:0 animated:NO];
    }
}

- (void)showInViewController:(UIViewController *)viewController
                    animated:(BOOL)animated
                  completion:(BottomPopupViewCompletion)completion {
    self.parentViewController = viewController;
    self.completion = completion;
    [kWindow addSubview:self];
    [self layoutIfNeeded];
    [self layoutSubviews];
    NSLog(@"%@",NSStringFromCGRect(self.containerView.frame));
    
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            // 显示背景遮罩
            self.backgroundButton.alpha = 0.5;
            
            // 向上移动容器视图
            CGRect containerFrame = self.containerView.frame;
            containerFrame.origin.y = self.bounds.size.height - containerFrame.size.height;
            self.containerView.frame = containerFrame;
            NSLog(@"%@",NSStringFromCGRect(self.containerView.frame));

        } completion:^(BOOL finished) {
//            if (completion) {
//                completion(self.selectedIndex, self.selectedIndex >= 0 && self.selectedIndex < self.items.count ? self.items[self.selectedIndex] : nil);
//            }
        }];
    } else {
        // 直接显示，不使用动画
        self.backgroundButton.alpha = 0.5;
        CGRect containerFrame = self.containerView.frame;
        containerFrame.origin.y = self.bounds.size.height - containerFrame.size.height;
        self.containerView.frame = containerFrame;
        
//        if (completion) {
//            completion(self.selectedIndex, self.selectedIndex >= 0 && self.selectedIndex < self.items.count ? self.items[self.selectedIndex] : nil);
//        }
    }
}

- (void)dismissAnimated:(BOOL)animated {
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            // 隐藏背景遮罩
            self.backgroundButton.alpha = 0.0;
            
            // 向下移动容器视图
            CGRect containerFrame = self.containerView.frame;
            containerFrame.origin.y = self.bounds.size.height;
            self.containerView.frame = containerFrame;
        } completion:^(BOOL finished) {
            // 从父视图中移除
            [self removeFromSuperview];
        }];
    } else {
        // 直接隐藏，不使用动画
        [self removeFromSuperview];
    }
}

- (void)backgroundButtonTapped {
    [self dismissAnimated:YES];
}

- (void)cancelButtonTapped {
    self.selectedIndex = -1; // 取消选择
    if (self.completion) {
        self.completion(self.selectedIndex, nil);
    }
    [self dismissAnimated:YES];
}

- (void)confirmButtonTapped {
    // 更新选中索引
    self.selectedIndex = [self.pickerView selectedRowInComponent:0];
    
    if (self.completion) {
        self.completion(self.selectedIndex, self.selectedIndex >= 0 && self.selectedIndex < self.items.count ? self.items[self.selectedIndex] : nil);
    }
    [self dismissAnimated:YES];
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.items.count;
}

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.items[row];
}
@end
